package cn.mesmile.juc.lock;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author zb
 * @date 2021/8/15 20:03
 * @Description 奇偶数
 */
public class OddAndEvenLock {

    public static void main(String[] args) {
        NumberSource numberSource = new NumberSource();
        // a 打印奇数  b 打印偶数
        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                numberSource.printOdd();
            }
        },"A").start();

        new Thread(()->{
            for (int i = 0; i < 20; i++) {
                numberSource.printEven();
            }
        },"B").start();
    }

}

class NumberSource {

    private int number = 0;

    ReentrantLock lock = new ReentrantLock();
    Condition condition = lock.newCondition();

    public void printOdd( ){
        // lock可重入锁，
        lock.lock();
        try {
            // while 避免虚假唤醒
            while (number % 2 == 0){
                condition.await();
            }
            // 操作
            System.out.println(Thread.currentThread().getName()+" 当前数字：" + number);
            number++;
            // 唤醒
            condition.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void printEven(){
        lock.lock();
        try {
            // while 避免虚假唤醒
            while (number % 2 != 0){
                condition.await();
            }
            // 操作
            System.out.println(Thread.currentThread().getName()+" 当前数字：" + number);
            number++;
            // 唤醒
            condition.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}

